package com.huixuebao.insure.controller;


import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.common.bean.RequestData;
import com.huixuebao.common.bean.ResponseData;
import com.huixuebao.common.enumeration.ResultCodeEnum;
import com.huixuebao.common.util.CommonUtil;
import com.huixuebao.common.util.JsonUtil;
import com.huixuebao.insure.common.config.GlobalConfig;
import com.huixuebao.insure.dto.CourseDTO;
import com.huixuebao.insure.entity.CourseEntity;
import com.huixuebao.insure.service.CourseService;
import com.huixuebao.common.util.RSASign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 * @author fatao_yu
 * @version 1.0
 * @date 2020-10-31 22:04
 */
@Slf4j
@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private GlobalConfig globalConfig;

    @GetMapping("/list")
    public ResponseData getCourseAttributes(@RequestParam("merchantUserNo") String merchantUserNo) {
        ResponseData responseData = new ResponseData();
        try{
            List<CourseEntity> list = courseService.listCourse(merchantUserNo);
            log.info("course list = {}", list);
            responseData = CommonUtil.getResponseData(list, globalConfig.getPrivateKey(),globalConfig.getDataKey());
        }catch (Exception e){
            log.error("获取机构课程属性异常: {}", e);
            responseData.setCode(ResultCodeEnum.FAILURE.getCode());
            responseData.setMessage(ResultCodeEnum.FAILURE.getMessage());
        }
        return responseData;
    }

    @GetMapping("/info")
    public CourseDTO getCourse(@RequestParam("id") String id) {
        return courseService.getCourse(id);
    }

    /**
     * @author fatao_yu
     * @return
     * 查询某个被保人是否存在某个课程
     */
    @PostMapping(value = "/exist")
    public ResponseData getCourse(@RequestBody RequestData requestData) {
        ResponseData responseData = new ResponseData(ResultCodeEnum.SUCCESS);
        try {
            boolean b = RSASign.verifyWhenSha1Sign(requestData.getData(), requestData.getSign(), globalConfig.getPublicKey());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isExist", true);
            responseData = CommonUtil.getResponseData(resultMap, globalConfig.getPrivateKey(),
                    globalConfig.getDataKey());
        } catch (Exception e) {
            log.error("解析异常：{}", e);
            responseData.setCode(ResultCodeEnum.FAILURE.getCode());
            responseData.setMessage(ResultCodeEnum.FAILURE.getMessage());
        }
        return responseData;
    }
}
